package util

import (
	"github.com/astaxie/beego/logs"
	"io/ioutil"
	"os"
)

// MakeDir Create a directory,if there has this directory, delete all files in this directory
func MakeDir(filePath string) error {
	_, err := os.Stat(filePath)
	if err != nil {
		logs.Error("os.Stat error:", err.Error())
		if os.IsNotExist(err) {
			logs.Info("And there is no such directory", filePath, "start to create")
			err = os.MkdirAll(filePath, os.ModePerm)
			if err != nil {
				logs.Error("os.MkdirAll error:", filePath, err.Error())
				return err
			}
			logs.Info("create directory success:", filePath)
			return nil
		}
		return err
	}

	fileList, err := ioutil.ReadDir(filePath)
	if err != nil {
		logs.Error("ReadDir error:", filePath, err.Error())
		return err
	}

	for _, file := range fileList {
		fileName := file.Name()
		childFilePath := filePath + fileName
		if file.IsDir() {
			err = os.RemoveAll(childFilePath)
			if err != nil {
				logs.Error("os.RemoveAll error:", childFilePath, err.Error())
				return err
			}
			logs.Info("directory deleted successfully")
		} else {
			err = os.Remove(childFilePath)
			if err != nil {
				logs.Error("os.Remove error:", childFilePath, err.Error())
				return err
			}
			logs.Info("Delete file successfully")
		}
	}
	return nil
}
